package com.jiangdg.demo

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class FolderAdapter(private val context: Context, private var folders: MutableList<File>,private val onItemSelectListener: ThumbnailAdapter.OnItemSelectListener) :
    RecyclerView.Adapter<FolderAdapter.FolderViewHolder>() {
    private val selectedItems = mutableSetOf<Int>()
    var editMode :Boolean = false

    inner class FolderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val folderNameTextView: TextView = itemView.findViewById(R.id.folder_name)
        val lastModifiedTextView: TextView = itemView.findViewById(R.id.last_modified)
        val thumbnailRecyclerView: RecyclerView = itemView.findViewById(R.id.thumbnail_recycler_view)
        val tvSelect: TextView = itemView.findViewById(R.id.tvSelect)
        val ivCheck: ImageView = itemView.findViewById(R.id.iv_check)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FolderViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.folder_item_layout, parent, false)
        return FolderViewHolder(itemView).apply {
            itemView.setOnClickListener {
                val folder = folders[adapterPosition]
                val intent = FileListActivity.createIntent(context, folder.absolutePath)
                context.startActivity(intent)
            }
            tvSelect.setOnClickListener {
                onItemSelectListener.onSelect(folders[adapterPosition])
            }

        }
    }

    override fun onBindViewHolder(holder: FolderViewHolder, position: Int) {
        val folder = folders[position]

        // Set folder name and last modified time
        holder.folderNameTextView.text = folder.name.split("~~~")[0]
        holder.lastModifiedTextView.text = SimpleDateFormat(context.getString(R.string.text_0018), Locale.getDefault())
            .format(Date(folder.lastModified()))

        holder.ivCheck.visibility = if (editMode) View.VISIBLE else View.GONE
        holder.ivCheck.setImageResource(
            if (selectedItems.contains(position)) R.drawable.icon_round_select else R.drawable.icon_round_un_select
        )

        holder.ivCheck.setOnClickListener {
            if (selectedItems.contains(position)) {
                selectedItems.remove(position)
                holder.ivCheck.setImageResource(R.drawable.icon_round_un_select)
            } else {
                selectedItems.add(position)
                holder.ivCheck.setImageResource(R.drawable.icon_round_select)
            }
            onItemSelectListener.onCheckChange(folders[position])
        }

        // Set up thumbnail RecyclerView for child images/videos
        holder.thumbnailRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        var childFiles = folder.listFiles() ?: emptyArray()
        childFiles = childFiles.sortedByDescending { it.lastModified() }.toTypedArray()
        val files = mutableListOf<File>()
        for (file in childFiles) {
            files.add(file)
        }
        holder.thumbnailRecyclerView.adapter = ThumbnailAdapter(context, files)
    }

    override fun getItemCount(): Int {
        return folders.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(folderList: MutableList<File>) {
        folders = folderList
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggle(){
        editMode = !editMode
        notifyDataSetChanged()
    }

    fun selectedAllItems() {
        selectedItems.clear()
        for (i in 0 until itemCount) {
            selectedItems.add(i)
        }
        notifyDataSetChanged()
    }

    fun deleteSelectedItems() {
        val itemsToDelete = selectedItems.sortedDescending().map { folders[it] }
        itemsToDelete.forEach {
            val delete = it.deleteRecursively()
            if (delete){
                folders.remove(it)
            }
        }
        selectedItems.clear()
        notifyDataSetChanged()
    }

    fun clearSelection() {
        selectedItems.clear()
        notifyDataSetChanged()
    }

    fun getSelectedItemCount(): Int {
        return selectedItems.size
    }
}

class ThumbnailAdapter(private val context: Context,private val files: List<File>) :
    RecyclerView.Adapter<ThumbnailAdapter.ThumbnailViewHolder>() {
    inner class ThumbnailViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val thumbnailImageView: ImageView = itemView.findViewById(R.id.thumbnail_image)
        val ivType: ImageView = itemView.findViewById(R.id.ivType)
        val ivDownload: ImageView = itemView.findViewById(R.id.ivDownload)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ThumbnailViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.thumbnail_item_layout, parent, false)
        return ThumbnailViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ThumbnailViewHolder, position: Int) {
        val requestOptions = RequestOptions().transform(CenterCrop(), RoundedCornersTransformation(20, 0))

        val file = files[position]
        holder.ivType.setImageResource(if (isPic(file))  R.mipmap.icon_pic else R.mipmap.icon_mp4)
        CoroutineScope(Dispatchers.Main).launch {
            Glide.with(context)
                .load(MediaCache.getMediaFrame(file.absolutePath,context))
                .transition(DrawableTransitionOptions.withCrossFade()) // Add cross-fade transition
                .apply(requestOptions)
                .into(holder.thumbnailImageView)
        }
        holder.ivDownload.setOnClickListener {
            if (isPic(file)){
                ImageSaver.saveImageToGallery(context,file.path)
            }else{
                ImageSaver.saveMp4ToGallery(context,file.path)
            }
        }
        holder.thumbnailImageView.setOnClickListener {
            if (isMp4(file)){
                //mp4
                VideoPopup(context, file).showPopupWindow()
            }
            if (isPic(file)){
                //pic
//                val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, Uri.fromFile(file))
//                ImagePopup(context, bitmap).showPopupWindow()
                val mutableList:MutableList<String> = mutableListOf()
                var currentPosition = 0
                var index = 0
                files.forEach {
                    if (isPic(it)){
                        mutableList.add(it.path)
                        if (it.path.equals(file.path)){
                            currentPosition = index
                        }
                    }
                    index++
                }
                val  intent = ImagePreviewActivity.createIntent(context, ArrayList(mutableList),currentPosition)
                context.startActivity(intent)
            }
        }

    }

    override fun getItemCount(): Int {
        return files.size
    }

    private fun isMp4(file: File):Boolean{
        return file.isFile && (file.extension.equals("mp4", ignoreCase = true) || file.extension.equals("avi", ignoreCase = true) || file.extension.equals("mkv", ignoreCase = true))
    }

    private fun isPic(file: File):Boolean{
        return file.extension.equals("jpg", ignoreCase = true) || file.extension.equals("jpeg", ignoreCase = true) || file.extension.equals("png", ignoreCase = true)
    }

    interface OnItemSelectListener{
        fun onSelect(file: File)
        fun onCheckChange(file: File)
    }
}
